package jt.classic.system.workflow;

import jt.classic.system.ISystem;
import jt.classic.system.SimpleAction;
import jt.classic.system.database.SystemDataSource;
import jt.classic.system.log.LogManager;
import jt.classic.system.user.IUser;
import jt.classic.system.utils.AnnexTool;
import jt.classic.system.wordbook.WordBookUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import org.limp.basework.SimpleBean;
import org.limp.basework.SimpleBean4Table;
import org.limp.basework.impl.CommonBean4HSQ;
import org.limp.basework.impl.SimpleBean4TableImpl;
import org.limp.basework.tools.BaseworkUtil;
import org.limp.basework.tools.SimpleBeanTransform;

import org.limp.mine.Controller;
import org.limp.mine.DataTrimmer;
import org.limp.mine.DataTrimmerI;
import org.limp.mine.Label;
import org.limp.mine.QueryJack;
import org.limp.mine.QueryJackFactory;
import org.limp.mine.StringTool;
import org.limp.mine.annex.AnnexInfo;

import java.sql.Connection;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 工作流程管理Action
 *
 * @author bizkit
 *
 */
public class WorkflowManageAction extends SimpleAction {
    /**
     * 流程类型列表
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward flowlist(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        CommonBean4HSQ cbh = new CommonBean4HSQ(request);

        Map param = cbh.getResource();

        String start = StringTool.checkString(param.get("start"), "0");

        String size = StringTool.checkString(param.get("limit"), "20");

        String pageNO = String.valueOf((Integer.parseInt(start) / Integer.parseInt(
                    size)) + 1);

        String sort = StringTool.checkString(param.get("sort"), "CG_ID");

        String dir = StringTool.checkString(param.get("dir"), "ASC");

        String sql1 = "SELECT COUNT(CG_ID) FROM WF_CATEGORY ";
        String sql2 = "SELECT * FROM WF_CATEGORY ORDER BY " + sort + " " + dir;

        String url = jt.classic.system.ISystem.getContextPath() +
            "/system/flowmanage.do?method=flowlist";

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            QueryJack plus = QueryJackFactory.getInstance().createQueryJack(false);

            // 设置
            plus.setParameter(QueryJackFactory.PAGINATION_SQL1, sql1);
            plus.setParameter(QueryJackFactory.PAGINATION_SQL2, sql2);
            plus.setParameter(QueryJackFactory.DATABASE_CONNECTION, conn);
            plus.setParameter(QueryJackFactory.PAGINATION_LINKSTRING, url);
            plus.setParameter(QueryJackFactory.PAGINATION_COUNT, "20");
            plus.setParameter(QueryJackFactory.PAGINATION_PAGENO, pageNO);

            // plus.setParameter(QueryJackFactory.PAGINATION_UPDATEPAGENO, "");
            List resultList = plus.work();

            if ((resultList != null) && !resultList.isEmpty()) {
                WObjectRegister or = WObjectRegister.getInstance();

                for (int i = 0; i < resultList.size(); i++) {
                    Map temp = (Map) resultList.get(i);
                    String oname = (String) temp.get("OBJ_NAME");

                    WObject obj = or.findWObject(oname);

                    temp.put("SURPORT", obj.isupport().iname());
                }
            }

            // 获得跳转控制
            Controller controller = plus.getController("form1");

            // 设置调转类型
            controller.setType("input");

            // 显示标签
            Label label = plus.getLabel();

            // 设置显示标签类型
            label.setType("href");

            Object[] result = new Object[4];
            result[0] = resultList;
            result[1] = label;
            result[2] = controller;
            result[3] = pageNO;

            JSONArray jsonArray = JSONArray.fromObject(resultList);

            String jsonString = "{\"totalCount\":\"" + label.totaldata() +
                "\",\"flowList\":";
            jsonString += jsonArray.toString();
            jsonString += "}";

            request.setAttribute("result", jsonString);
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("jsonresult");
    }

    /**
     * 编辑流程类别
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward editflow(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        String id = StringTool.checkString(request.getParameter("id"));

        Connection conn = null;

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            DataTrimmer trimmer = new DataTrimmer(conn);

            String sql = "SELECT * FROM WF_CATEGORY WHERE CG_ID = " + id;

            Map info = trimmer.searchSingleData(sql);

            if (info != null) {
                String objkey = (String) info.get("OBJ_NAME");

                WObjectRegister register = WObjectRegister.getInstance();
                WObject obj = register.findWObject(objkey);

                if (obj != null) {
                    request.setAttribute("result",
                        "{success: true, data :{gid:'" + info.get("CG_ID") +
                        "',ikey:'" + info.get("CG_KEY") + "',iname:'" +
                        info.get("CG_NAME") + "',imemo:'" +
                        info.get("CG_MEMO") + "',iobj:'" + objkey +
                        "',iobjname:'" + obj.iname() + "'}}");
                } else {
                    request.setAttribute("result",
                        "{success: false, result : 1}");
                }
            } else {
                request.setAttribute("result", "{success: false, result : 0}");
            }
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);

            request.setAttribute("result", "{success: false, result : -1}");
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("result");
    }

    /**
     * 保存流程类别
     *
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward saveflow(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        try {
            CommonBean4HSQ cbh = new CommonBean4HSQ(request);

            Map param = cbh.getResource();

            String key = StringTool.checkString(param.get("ikey"));

            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            WorkflowManager wfmanager = new WorkflowManager(conn);

            boolean rnt = wfmanager.containsKey(key);

            if (!rnt) {
                BaseworkUtil util = new BaseworkUtil();

                SimpleBean sb = BaseworkUtil.analyzerSimpleBean("WF_CATEGORY",
                        cbh);

                util.manualSave("WF_CATEGORY", sb, conn);

                conn.commit();

                request.setAttribute("result", "{success: true}");
            } else {
                request.setAttribute("result", "{success: false, result : 0}");
            }
        } catch (Exception ex) {
            request.setAttribute("result", "{success: false, result : -1}");
            conn.rollback();
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("result");
    }

    /**
     * 复制流程类别
     *
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward copyflow(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        try {
            CommonBean4HSQ cbh = new CommonBean4HSQ(request);

            Map param = cbh.getResource();

            String key = StringTool.checkString(param.get("ikey"));

            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            WorkflowManager wfmanager = new WorkflowManager(conn);

            boolean rnt = wfmanager.containsKey(key);

            if (!rnt) {
                String name = StringTool.checkString(param.get("iname"));
                String object = StringTool.checkString(param.get("iobj"));
                String fid = StringTool.checkString(param.get("icopyid"));

                wfmanager.copy(name, key, object, fid);

                conn.commit();

                request.setAttribute("result", "{success: true}");
            } else {
                request.setAttribute("result", "{success: false, result : 0}");
            }
        } catch (Exception ex) {
            request.setAttribute("result", "{success: false, result : -1}");
            conn.rollback();
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("result");
    }

    /**
     * 修改流程类别
     *
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward updateflow(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        try {
            CommonBean4HSQ cbh = new CommonBean4HSQ(request);

            Map param = cbh.getResource();

            String gid = StringTool.checkString(param.get("gid"));

            String key = StringTool.checkString(param.get("ikey"));

            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            String sql = "SELECT CG_KEY FROM WF_CATEGORY WHERE CG_ID <> " +
                gid + " AND CG_KEY = '" + key + "'";

            DataTrimmer trimmer = new DataTrimmer(conn);

            if (!trimmer.haveMoreData(sql)) {
                BaseworkUtil util = new BaseworkUtil();

                SimpleBean sb = BaseworkUtil.analyzerSimpleBean("WF_CATEGORY",
                        cbh);

                util.manualUpdate("WF_CATEGORY", sb, conn);

                conn.commit();

                request.setAttribute("result", "{success: true}");
            } else {
                request.setAttribute("result", "{success: false, result : 0}");
            }
        } catch (Exception ex) {
            request.setAttribute("result", "{success: false, result : -1}");
            conn.rollback();
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("result");
    }

    /**
     * 删除流程类别
     *
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward deleteflow(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        IUser user = ISystem.getSessionUser(request);

        String gid = StringTool.checkString(request.getParameter("gid"));

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            WorkflowManager wmanager = new WorkflowManager(conn);

            WFlow flow = wmanager.getWFlowById(gid);

            WorkflowEngine engine = new WorkflowEngine(conn);
            engine.reinit(flow, user);

            wmanager.deleteFlow(gid);

            conn.commit();

            request.setAttribute("result", "{success: true}");
        } catch (Exception ex) {
            request.setAttribute("result", "{success: false, result : -1}");
            conn.rollback();
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("result");
    }

    /**
     * 工作流程重新初始化
     *
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward reinit(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        IUser user = ISystem.getSessionUser(request);

        String id = StringTool.checkString(request.getParameter("id"));

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            WorkflowManager manager = new WorkflowManager(conn);

            WFlow flow = manager.getWFlowById(id);

            WorkflowEngine engine = new WorkflowEngine(conn);
            engine.reinit(flow, user);

            conn.commit();

            request.setAttribute("result", "{success: true}");
        } catch (Exception ex) {
            request.setAttribute("result", "{success: false}");
            conn.rollback();
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("result");
    }

    /**
     * 流程xml脚本便于绘图
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward preplotter(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        ActionForward forward = null;

        String id = StringTool.checkString(request.getParameter("id"));

        String type = StringTool.checkString(request.getParameter("type"));

        if (type.equals("")) {
            type = "viewing";
        }

        Connection conn = null;

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            WorkflowManager manager = new WorkflowManager(conn);
            WFlow flow = manager.getWFlowById(id);

            request.setAttribute("type", type);
            request.setAttribute("flow", flow);

            if (type.equals("viewing")) {
                /*实例ID*/
                String insid = StringTool.checkString(request.getParameter(
                            "insid"));

                /*当前活动记录ID*/
                String currentActId = StringTool.checkString(request.getParameter(
                            "currentActId"));

                if (!insid.equals("")) {
                    WInstanceManager imanager = new WInstanceManager(conn);
                    WInstance instance = imanager.getInstanceByID(insid);

                    if (instance != null) {
                        String xml = instance.toXML(0);

                        if (currentActId.equals("")) {
                            currentActId = instance.imaxactivity().id();
                        }

                        request.setAttribute("insid", insid);
                        request.setAttribute("currentActId", currentActId);
                        request.setAttribute("instanceProcessXML", xml);
                    }
                }
            }

            forward = mapping.findForward("preplotter");
        } catch (Exception ex) {
            forward = mapping.findForward("error");
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return forward;
    }

    /**
     * 流程环节列表
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return ActionForward
     * @throws Exception
     */
    public ActionForward steplist(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        CommonBean4HSQ cbh = new CommonBean4HSQ(request);

        Map param = cbh.getResource();

        String start = StringTool.checkString(param.get("start"), "0");

        String size = StringTool.checkString(param.get("limit"), "20");

        String pageNO = String.valueOf((Integer.parseInt(start) / Integer.parseInt(
                    size)) + 1);

        String gid = StringTool.checkString(request.getParameter("gid"));

        String sort = StringTool.checkString(param.get("sort"), "S_NO");

        String dir = StringTool.checkString(param.get("dir"), "ASC");

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            String sql1 = "SELECT COUNT(S_ID) FROM WF_STEP WHERE CG_ID = " +
                gid;
            String sql2 = "SELECT * FROM WF_STEP WHERE CG_ID = " + gid +
                " ORDER BY " + sort + " " + dir;

            QueryJack plus = QueryJackFactory.getInstance().createQueryJack(false);

            // 设置
            plus.setParameter(QueryJackFactory.PAGINATION_SQL1, sql1);
            plus.setParameter(QueryJackFactory.PAGINATION_SQL2, sql2);
            plus.setParameter(QueryJackFactory.DATABASE_CONNECTION, conn);
            plus.setParameter(QueryJackFactory.PAGINATION_LINKSTRING, "");
            plus.setParameter(QueryJackFactory.PAGINATION_COUNT, "20");
            plus.setParameter(QueryJackFactory.PAGINATION_PAGENO, pageNO);

            // plus.setParameter(QueryJackFactory.PAGINATION_UPDATEPAGENO, "");
            List resultList = plus.work();

            if ((resultList != null) && !resultList.isEmpty()) {
                for (int i = 0; i < resultList.size(); i++) {
                    Map info = (Map) resultList.get(i);

                    String inner = (String) info.get("S_INNER");

                    info.put("S_INNERNAME",
                        WordBookUtil.getWordBookItemName("inner-type", inner));

                    String type = (String) info.get("S_TYPE");

                    info.put("S_TYPENAME",
                        WordBookUtil.getWordBookItemName("step-type", type));
                }
            }

            // 获得跳转控制
            Controller controller = plus.getController("form1");

            // 设置调转类型
            controller.setType("input");

            // 显示标签
            Label label = plus.getLabel();

            // 设置显示标签类型
            label.setType("href");

            Object[] result = new Object[4];
            result[0] = resultList;
            result[1] = label;
            result[2] = controller;
            result[3] = pageNO;

            JSONArray jsonArray = JSONArray.fromObject(resultList);

            String jsonString = "{\"totalCount\":\"" + label.totaldata() +
                "\",\"stepList\":";
            jsonString += jsonArray.toString();
            jsonString += "}";

            request.setAttribute("result", jsonString);
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("jsonresult");
    }

    /**
     * 流向环节列表
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return ActionForward
     * @throws Exception
     */
    public ActionForward trendlist(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        CommonBean4HSQ cbh = new CommonBean4HSQ(request);

        Map param = cbh.getResource();

        String start = StringTool.checkString(param.get("start"), "0");

        String size = StringTool.checkString(param.get("limit"), "20");

        String pageNO = String.valueOf((Integer.parseInt(start) / Integer.parseInt(
                    size)) + 1);

        String sid = StringTool.checkString(request.getParameter("sid"));

        String sort = StringTool.checkString(param.get("sort"), "S_NO");

        String dir = StringTool.checkString(param.get("dir"), "ASC");

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            DataTrimmer trimmer = new DataTrimmer(conn);

            String sql2 =
                "SELECT WF_STEP.* FROM WF_STEP,WF_TREND WHERE WF_STEP.S_ID = WF_TREND.TREND_ID AND WF_TREND.S_ID = " +
                sid + " ORDER BY " + sort + " " + dir;

            List resultList = trimmer.searchMultiData(sql2);

            if ((resultList != null) && !resultList.isEmpty()) {
                for (int i = 0; i < resultList.size(); i++) {
                    Map info = (Map) resultList.get(i);

                    String inner = (String) info.get("S_INNER");

                    info.put("S_INNERNAME",
                        WordBookUtil.getWordBookItemName("inner-type", inner));

                    String type = (String) info.get("S_TYPE");

                    info.put("S_TYPENAME",
                        WordBookUtil.getWordBookItemName("step-type", type));
                }
            }

            JSONArray jsonArray = JSONArray.fromObject(resultList);

            String jsonString = "{\"totalCount\":\"" + resultList.size() +
                "\",\"stepList\":";
            jsonString += jsonArray.toString();
            jsonString += "}";

            request.setAttribute("result", jsonString);
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("jsonresult");
    }

    /**
     * 编辑环节
     *
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return ActionForward
     * @throws Exception
     */
    public ActionForward editstep(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        String id = StringTool.checkString(request.getParameter("id"));

        Connection conn = null;

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            WorkflowManager manager = new WorkflowManager(conn);

            WStep step = manager.getStepByID(id);

            request.setAttribute("step", step);
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("editstep");
    }

    /**
     * 修改环节信息
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return ActionForward
     * @throws Exception
     */
    public ActionForward updatestep(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        CommonBean4HSQ cbh = new CommonBean4HSQ(request);

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            SimpleBean4Table sbt = new SimpleBean4TableImpl("WF_STEP", cbh);

            BaseworkUtil util = new BaseworkUtil();

            util.manualUpdate1(sbt, conn);

            conn.commit();

            request.setAttribute("result", "{success: true}");
        } catch (Exception ex) {
            request.setAttribute("result", "{success: false, result : -1}");
            conn.rollback();
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("result");
    }

    /**
     * 删除环节信息
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return ActionForward
     * @throws Exception
     */
    public ActionForward deletestep(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        IUser user = ISystem.getSessionUser(request);

        CommonBean4HSQ cbh = new CommonBean4HSQ(request);

        Map param = (Map) cbh.getResource();

        String id = (String) param.get("id");

        String name = (String) param.get("name");

        String fname = (String) param.get("fname");

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            WorkflowManager manager = new WorkflowManager(conn);

            manager.deleteStep(id);

            LogManager log = new LogManager(conn);

            log.log(user, request.getRemoteAddr(), "", "", "deleteStep",
                "delete", "删除流程[" + fname + "]的环节[" + id + "," + name + "]");

            conn.commit();

            request.setAttribute("result", "{success: true}");
        } catch (Exception ex) {
            request.setAttribute("result", "{success: false, result : -1}");
            conn.rollback();
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("result");
    }

    /**
     * 编辑环节操作对象权限
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward editstate(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        String sid = StringTool.checkString(request.getParameter("sid"));
        String gid = StringTool.checkString(request.getParameter("gid"));

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            WorkflowManager manager = new WorkflowManager(conn);

            WFlow flow = manager.getWFlowById(gid);

            WStep step = flow.istep(sid);

            request.setAttribute("flow", flow);
            request.setAttribute("step", step);
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("editstate");
    }

    /**
     * 修改环节操作对象权限
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward updatestate(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        CommonBean4HSQ cbh = new CommonBean4HSQ(request);

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            BaseworkUtil util = new BaseworkUtil();

            List list = util.analyzerSimpleBean1("WF_HANDLE", "countName", cbh);

            util.manualRemixX1(list, conn);

            conn.commit();

            request.setAttribute("result", "{success: true}");
        } catch (Exception ex) {
            request.setAttribute("result", "{success: false, result : -1}");

            conn.rollback();
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("result");
    }

    /**
     * 文号列表
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward numberlist(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        CommonBean4HSQ cbh = new CommonBean4HSQ(request);

        Map param = cbh.getResource();

        String start = StringTool.checkString(param.get("start"), "0");

        String size = StringTool.checkString(param.get("limit"), "20");

        String pageNO = String.valueOf((Integer.parseInt(start) / Integer.parseInt(
                    size)) + 1);

        String sql1 = "SELECT COUNT(PKID) FROM WF_NUMBER_TYPE";

        String sql2 = "SELECT * FROM WF_NUMBER_TYPE ORDER BY PKID";

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            QueryJack plus = QueryJackFactory.getInstance().createQueryJack(false);

            // 设置
            plus.setParameter(QueryJackFactory.PAGINATION_SQL1, sql1);
            plus.setParameter(QueryJackFactory.PAGINATION_SQL2, sql2);
            plus.setParameter(QueryJackFactory.DATABASE_CONNECTION, conn);
            plus.setParameter(QueryJackFactory.PAGINATION_LINKSTRING, "");
            plus.setParameter(QueryJackFactory.PAGINATION_COUNT, "20");
            plus.setParameter(QueryJackFactory.PAGINATION_PAGENO, pageNO);

            // plus.setParameter(QueryJackFactory.PAGINATION_UPDATEPAGENO, "");
            List resultList = plus.work();
            JSONArray jsonArray = JSONArray.fromObject(resultList);

            // 显示标签
            Label label = plus.getLabel();

            String jsonString = "{\"totalCount\":\"" + label.totaldata() +
                "\",\"numberList\":";
            jsonString += jsonArray.toString();
            jsonString += "}";

            request.setAttribute("result", jsonString);
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("jsonresult");
    }

    /**
     * 保存文号
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return ActionForward
     * @throws Exception
     */
    public ActionForward savenumber(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        CommonBean4HSQ cbh = new CommonBean4HSQ(request);

        Map param = cbh.getResource();

        String gid = (String) param.get("objid");

        String wobject = (String) param.get("wobject");

        String sql = "SELECT PKID FROM WF_NUMBER_TYPE WHERE OBJ_ID = ? AND WOBJECT = ?";

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            DataTrimmerI trimmer = new DataTrimmerI(conn);

            DataTrimmerI.DataItemList dil = trimmer.createDIL();
            dil.set(gid);
            dil.set(wobject);

            if (trimmer.haveMoreData(sql, dil)) {
                request.setAttribute("result", "{success: false, result : 0}");
            } else {
                SimpleBean4Table sbt = new SimpleBean4TableImpl("WF_NUMBER_TYPE",
                        cbh);

                BaseworkUtil util = new BaseworkUtil();

                util.manualSave1(sbt, conn);

                conn.commit();

                request.setAttribute("result", "{success: true}");
            }
        } catch (Exception ex) {
            request.setAttribute("result", "{success: false, result : -1}");
            conn.rollback();
            ISystem.catchException(ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("result");
    }

    /**
     * 编辑文号
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return ActionForward
     * @throws Exception
     */
    public ActionForward editnumber(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        String id = request.getParameter("id");

        String sql = "SELECT * FROM WF_NUMBER_TYPE WHERE PKID = ?";

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            DataTrimmerI trimmer = new DataTrimmerI(conn);

            DataTrimmerI.DataItemList dil = trimmer.createDIL();
            dil.set(id);

            Map info = trimmer.searchSingleData(sql, dil);

            info.put("_gname", info.get("OBJ_NAME"));

            String wobject = (String) info.get("WOBJECT");

            WObject obj = WObjectRegister.getInstance().findWObject(wobject);

            info.put("wobjectName", obj.iname());

            info.put("_oname", obj.iname());

            SimpleBean4Table sbt = new SimpleBean4TableImpl("WF_NUMBER_TYPE");

            sbt.reload(info);

            SimpleBeanTransform.trunRight(sbt, sbt.getTable());

            JSONObject json = JSONObject.fromObject(sbt.getResource());

            String jsonString = "{success: true, data:";
            jsonString += json.toString();
            jsonString += "}";

            request.setAttribute("result", jsonString);
        } catch (Exception ex) {
            request.setAttribute("result", "{success: false, result : -1}");
            ISystem.catchException(ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("result");
    }

    /**
     * 修改文号
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return ActionForward
     * @throws Exception
     */
    public ActionForward updatenumber(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        CommonBean4HSQ cbh = new CommonBean4HSQ(request);

        Map param = cbh.getResource();

        String pkid = (String) param.get("pkid");

        String gid = (String) param.get("objid");

        String wobject = (String) param.get("wobject");

        String sql = "SELECT PKID FROM WF_NUMBER_TYPE WHERE OBJ_ID = ? AND WOBJECT = ? AND PKID <> ?";

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            DataTrimmerI trimmer = new DataTrimmerI(conn);

            DataTrimmerI.DataItemList dil = trimmer.createDIL();
            dil.set(gid);
            dil.set(wobject);
            dil.set(pkid);

            if (trimmer.haveMoreData(sql, dil)) {
                request.setAttribute("result", "{success: false, result : 0}");
            } else {
                SimpleBean4Table sbt = new SimpleBean4TableImpl("WF_NUMBER_TYPE",
                        cbh);

                BaseworkUtil util = new BaseworkUtil();

                util.manualUpdate1(sbt, conn);

                conn.commit();

                request.setAttribute("result", "{success: true}");
            }
        } catch (Exception ex) {
            request.setAttribute("result", "{success: false, result : -1}");
            conn.rollback();
            ISystem.catchException(ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("result");
    }

    /**
     * 删除文号
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return ActionForward
     * @throws Exception
     */
    public ActionForward deletenumber(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        String id = request.getParameter("id");

        String sql = "DELETE FROM WF_NUMBER_TYPE WHERE PKID = ?;DELETE FROM WF_NUMBER WHERE PKID = ?";

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            DataTrimmerI trimmer = new DataTrimmerI(conn);

            DataTrimmerI.DataItemList dil = trimmer.createDIL();
            dil.set(id);

            List list = new ArrayList();
            list.add(dil);
            list.add(dil);

            trimmer.executeBatch(sql, list);

            conn.commit();
            request.setAttribute("result", "{success: true}");
        } catch (Exception ex) {
            request.setAttribute("result", "{success: false, result : -1}");
            conn.rollback();
            ISystem.catchException(ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("result");
    }

    /**
     * 正文模板列表
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward doclist(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        CommonBean4HSQ cbh = new CommonBean4HSQ(request);

        Map param = cbh.getResource();

        String fid = (String) param.get("fid");

        String sql = "SELECT * FROM WF_DOCTEMP WHERE CG_ID = ? ORDER BY TEMP_NAME";

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            DataTrimmerI trimmer = new DataTrimmerI(conn);

            DataTrimmerI.DataItemList dil = trimmer.createDIL();

            dil.set(fid);

            List list = trimmer.searchMultiData(sql, dil);

            if ((list != null) && !list.isEmpty()) {
                AnnexTool tool = new AnnexTool(conn);

                for (int i = 0; i < list.size(); i++) {
                    Map info = (Map) list.get(i);

                    String docid = (String) info.get("TEMP_ID");

                    AnnexInfo[] annexs = tool.getAnnexs(docid, "WF_DOCTEMP");

                    if ((annexs != null) && (annexs.length > 0)) {
                        info.put("ANNEXID", annexs[0].getID());
                    }
                }
            }

            JSONArray jsonArray = JSONArray.fromObject(list);

            String jsonString = "{\"totalCount\":\"" + list.size() +
                "\",\"docList\":";
            jsonString += jsonArray.toString();
            jsonString += "}";

            request.setAttribute("result", jsonString);
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("jsonresult");
    }
}
